package try01;

import java.util.*;

public class TextJustification {
	public void tester() {
		
		int x = -100;
		System.out.println(Math.sqrt(-100));
		
//		String [] a = {"a","b","c","d","e"};
//		List<String> b = fullJustify(a, 5);
//		System.out.println(b.get(0));
//		System.out.println(b.get(1));
//		System.out.println(b.get(2));
	}
    public List<String> fullJustify(String[] words, int L) {
        List <String> output = new LinkedList<String>();
        
        int a = 0, b = 0;
        while(b < words.length) {
            if(b+1 >= words.length) { // b is pointing to the last word
                output.add(formstring(words,a,b,L));
                break;
            }
            else { // b is not pointing to the last word
                if(countLength(words, a, b + 1) + (b+1-a) <= L) {
                    b++;
                }
                else {
                    output.add(formstring(words,a,b,L));
                    a = b+1;
                    b = b+1;
                }
            }
        }
        
        return output;
    }
    
    public int countLength(String [] words, int a, int b) {
        int sum = 0;
        for(int i = a; i <= b ; i++) {
            sum = sum + words[i].length();
        }
        return sum;
    }
    
    public String formstring(String [] words, int a, int b, int L) {
        int sum = countLength(words, a, b);

        if(a == b) return words[a]+formspace(L-sum);
        
        int remain = (L-sum)%(b-a);
        int count = (L-sum)/(b-a);
        
        if(b == words.length - 1) {
        	remain = 0;
        	count = 1;
        }
        
        String output = "";
        
        for(int i = a ; i < b ; i++) {
            output = output + words[i]+formspace(count);
            if(remain > 0) {
                remain --;
                output = output +" ";
            }
        }
        output = output + words[b];
        
        while(output.length() < L) {
        	output = output + " ";
        }
        
        return output;
    }
    
    public String formspace(int a) {
        String output = "";
        for(int i = 0 ; i < a ; i++) {
            output = output + " ";
        }
        return output;
    }
}